<template>
  <div class="class-list-container">
    <div class="header-section">
      <h1 class="list-title">班级列表</h1>
      <div class="action-buttons">
        <el-button 
          type="primary" 
          size="large"
          @click="refreshList"
          :loading="loading"
          class="refresh-btn"
        >
          <el-icon><Refresh /></el-icon>
          <span>刷新列表</span>
        </el-button>
      </div>
    </div>
    
    <!-- 搜索和过滤区域 -->
    <div class="filter-section">
      <el-input
        v-model="searchText"
        placeholder="输入班级名称或ID搜索"
        clearable
        class="search-input"
        size="large"
        @input="handleSearch"
      >
        <template #prefix>
          <el-icon><Search /></el-icon>
        </template>
      </el-input>
      
      <div class="filter-actions">
        <el-select
          v-model="sortField"
          placeholder="排序字段"
          class="sort-select"
          size="large"
          @change="handleSortChange"
        >
          <el-option label="按ID排序" value="id"></el-option>
          <el-option label="按名称排序" value="className"></el-option>
          <el-option label="按人数排序" value="classStuNum"></el-option>
          <el-option label="按创建时间排序" value="createTime"></el-option>
        </el-select>
        
        <el-select
          v-model="sortOrder"
          placeholder="排序方式"
          class="sort-order"
          size="large"
          @change="handleSortChange"
        >
          <el-option label="升序" value="asc"></el-option>
          <el-option label="降序" value="desc"></el-option>
        </el-select>
      </div>
    </div>
    
    <!-- 班级表格 -->
    <div class="table-section">
      <el-table 
        :data="paginatedData" 
        v-loading="loading"
        :cell-style="{ fontSize: '18px', padding: '16px 0' }"
        :header-cell-style="{ 
          fontSize: '18px', 
          fontWeight: 'bold',
          backgroundColor: '#f8f9fa',
          padding: '16px 0'
        }"
        border
        stripe
        highlight-current-row
        @row-click="handleRowClick"
        style="width: 100%"
      >
        <el-table-column 
          prop="id" 
          label="班级ID" 
          width="180"
          sortable
        ></el-table-column>
        
        <el-table-column 
          prop="className" 
          label="班级名称" 
          width="280"
          sortable
        ></el-table-column>
        
        <el-table-column 
          prop="classStuNum" 
          label="学生人数"
          width="200"
          sortable
        >
          <template #default="scope">
            <el-tag 
              :type="getStudentCountTagType(scope.row.classStuNum)"
              class="student-count"
              size="large"
            >
              {{ scope.row.classStuNum }}人
            </el-tag>
          </template>
        </el-table-column>
        
        <el-table-column 
          prop="createTime" 
          label="创建时间" 
          width="280"
          sortable
        >
          <template #default="scope">
            <span class="create-time">
              {{ formatDate(scope.row.createTime) }}
            </span>
          </template>
        </el-table-column>
        
        <el-table-column 
          label="操作" 
          width="200"
          fixed="right"
        >
          <template #default="scope">
            <el-button 
              type="primary" 
              size="large"
              @click.stop="viewClass(scope.row)"
              class="view-btn"
            >
              <el-icon><View /></el-icon>
              <span>查看详情</span>
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    
    <!-- 分页组件 -->
    <div class="pagination-section">
      <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :page-sizes="[10, 20, 50, 100]"
        :background="true"
        layout="total, sizes, prev, pager, next, jumper"
        :total="filteredData.length"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        class="custom-pagination"
      />
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { Search, Refresh, View } from '@element-plus/icons-vue'
import { classApi } from '@/api/class'
import { teacherApi } from '@/api/teacher'
import { useAuthStore } from '@/stores/auth'
import { useRouter } from 'vue-router'

const router = useRouter()
const authStore = useAuthStore()

// 数据状态
const classList = ref([])
const loading = ref(false)
const searchText = ref('')

// 排序相关
const sortField = ref('id')
const sortOrder = ref('asc')

// 分页相关
const currentPage = ref(1)
const pageSize = ref(10)

// 获取班级列表
const fetchClassList = async () => {
  loading.value = true
  try {
    const response = await classApi.getClassList()
    classList.value = response.data || response
    // 初始排序
    handleSortChange()
  } catch (error) {
    console.error('获取班级列表失败:', error)
    ElMessage.error('获取班级列表失败')
  } finally {
    loading.value = false
  }
}

// 刷新列表
const refreshList = () => {
  currentPage.value = 1
  fetchClassList()
}

// 格式化日期
const formatDate = (dateString) => {
  if (!dateString) return ''
  const date = new Date(dateString)
  return date.toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit'
  }).replace(/\//g, '-')
}

// 学生人数标签类型
const getStudentCountTagType = (count) => {
  if (count === 0) return 'info'
  if (count < 20) return ''
  if (count < 50) return 'success'
  return 'warning'
}

// 排序处理
const handleSortChange = () => {
  classList.value.sort((a, b) => {
    let comparison = 0
    
    if (sortField.value === 'createTime') {
      const dateA = new Date(a[sortField.value])
      const dateB = new Date(b[sortField.value])
      comparison = dateA - dateB
    } else {
      if (a[sortField.value] < b[sortField.value]) comparison = -1
      if (a[sortField.value] > b[sortField.value]) comparison = 1
    }
    
    return sortOrder.value === 'asc' ? comparison : -comparison
  })
}

// 搜索功能
const filteredData = computed(() => {
  if (!searchText.value) return classList.value
  return classList.value.filter(item => 
    item.className.toLowerCase().includes(searchText.value.toLowerCase()) ||
    String(item.id).includes(searchText.value)
  )
})

// 分页数据
const paginatedData = computed(() => {
  const start = (currentPage.value - 1) * pageSize.value
  const end = start + pageSize.value
  return filteredData.value.slice(start, end)
})

// 行点击事件
const handleRowClick = (row) => {
  viewClass(row)
}

// 查看班级
const viewClass = async (classItem) => {
  try {
    // 1. 获取当前用户ID
    const userId = authStore.userId
    if (!userId) {
      ElMessage.warning('请先登录')
      return
    }

    // 2. 获取教师ID
    const teacherRes = await teacherApi.getTeacherByUid(userId)
    const teacherId = teacherRes.data?.id || teacherRes.id
    
    if (!teacherId) {
      ElMessage.warning('当前用户未关联教师账号')
      return
    }

    // 3. 检查权限
    const hasPermission = await classApi.checkTeacherClass(teacherId, classItem.id)
    
    // 4. 跳转
    await router.push({
      name: 'ClassInfo',
      params: { 
        id: classItem.id,
        _: Date.now() // 防缓存
      },
      state: {
        classData: {
          ...classItem,
          hasPermission: Boolean(hasPermission?.data ?? hasPermission),
          teacherId
        }
      }
    })

  } catch (error) {
    console.error('查看班级失败:', error)
    ElMessage.error(`操作失败: ${error.message}`)
  }
}

// 搜索处理
const handleSearch = () => {
  currentPage.value = 1
}

// 分页处理
const handleSizeChange = (newSize) => {
  pageSize.value = newSize
  currentPage.value = 1
}

const handleCurrentChange = (newPage) => {
  currentPage.value = newPage
}

// 初始化加载数据
onMounted(() => {
  fetchClassList()
})
</script>

<style scoped>
.class-list-container {
  padding: 32px;
  background-color: #fff;
  border-radius: 12px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.08);
  min-height: calc(100vh - 120px);
  max-width: 1600px;
  margin: 0 auto;
}

.header-section {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 32px;
  padding-bottom: 24px;
  border-bottom: 1px solid #ebeef5;
}

.list-title {
  font-size: 28px;
  font-weight: 600;
  color: #303133;
  margin: 0;
  letter-spacing: 1px;
}

.action-buttons {
  display: flex;
  gap: 16px;
}

.filter-section {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 28px;
  gap: 24px;
}

.search-input {
  width: 400px;
}

.filter-actions {
  display: flex;
  gap: 16px;
}

.sort-select,
.sort-order {
  width: 180px;
}

.table-section {
  margin: 24px 0;
}

.student-count {
  font-weight: bold;
  min-width: 80px;
  text-align: center;
  display: inline-block;
  font-size: 16px;
  padding: 8px 12px;
}

.create-time {
  color: #606266;
  font-size: 16px;
}

.view-btn {
  display: inline-flex;
  align-items: center;
  gap: 8px;
  padding: 12px 20px;
  font-size: 16px;
}

.refresh-btn {
  padding: 12px 24px;
  font-size: 16px;
}

.pagination-section {
  margin-top: 32px;
  display: flex;
  justify-content: center;
}

/* 表格行悬停效果 */
:deep(.el-table__row:hover) {
  cursor: pointer;
  background-color: #f5f7fa !important;
}

/* 分页样式优化 */
:deep(.custom-pagination) {
  padding: 20px 0;
}

:deep(.custom-pagination .el-pagination__total),
:deep(.custom-pagination .el-pagination__jump) {
  font-size: 16px;
}

:deep(.custom-pagination .el-pagination.is-background .el-pager li:not(.is-disabled).is-active) {
  background-color: #409eff;
  color: white;
  font-size: 16px;
  min-width: 36px;
  height: 36px;
  line-height: 36px;
}

:deep(.custom-pagination .el-pagination.is-background .el-pager li:not(.is-disabled):hover) {
  color: #409eff;
}

:deep(.custom-pagination .el-pagination__sizes .el-input__inner) {
  font-size: 16px;
  height: 36px;
}

:deep(.custom-pagination .el-pagination__jump .el-input__inner) {
  font-size: 16px;
  height: 36px;
}

/* 响应式调整 */
@media (max-width: 1200px) {
  .class-list-container {
    padding: 24px;
  }
  
  .header-section {
    flex-direction: column;
    align-items: flex-start;
    gap: 20px;
  }
  
  .filter-section {
    flex-direction: column;
    align-items: flex-start;
  }
  
  .search-input {
    width: 100%;
  }
  
  .filter-actions {
    width: 100%;
    justify-content: space-between;
  }
  
  .sort-select,
  .sort-order {
    width: 48%;
  }
}

@media (max-width: 992px) {
  :deep(.el-table) {
    font-size: 16px;
  }
  
  :deep(.el-table th.el-table__cell),
  :deep(.el-table td.el-table__cell) {
    padding: 12px 0;
  }
  
  .list-title {
    font-size: 24px;
  }
}

@media (max-width: 768px) {
  .class-list-container {
    padding: 16px;
  }
  
  :deep(.el-table) {
    font-size: 14px;
  }
  
  :deep(.action-btn) {
    padding: 8px 12px;
    font-size: 14px;
  }
  
  .list-title {
    font-size: 22px;
  }
}
</style>